//
//  TitleButton.m
//  EPTool
//
//  Created by guoshiqing on 2018/4/27.
//  Copyright © 2018年 云数动能科技. All rights reserved.
//

#import "TitleButton.h"


#define Margin 4
#define MaxLblLenth 180.0f
#define MaxBtnLenth 220.0f

@implementation TitleButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    CGRect frameLabel = self.titleLabel.frame;
    CGRect frameImage = self.imageView.frame;
    
    // 设置最大宽度
    if (MaxLblLenth < frameLabel.size.width) {
        frameLabel.size.width = MaxLblLenth;
        self.titleLabel.frame = frameLabel;
    }
    
    // 设置图片和设置按钮调用sizeToFit都会进入这个函数，会交换两次，只要保证文字在左边就不交换了
    if (frameLabel.origin.x > frameImage.origin.x) {
        frameLabel.origin.x = frameImage.origin.x;
        self.titleLabel.frame = frameLabel;
        
        // 2.计算imageView的frame
        frameImage.origin.x = CGRectGetMaxX(self.titleLabel.frame) + Margin;
        self.imageView.frame = frameImage;
    }
    
    CGRect frameButton = self.frame;
    if (MaxBtnLenth < frameButton.size.width) {
        frameButton.size.width = MaxBtnLenth;
        self.frame = frameButton;
    }
}

- (void)setTitle:(NSString *)title forState:(UIControlState)state
{
    [super setTitle:title forState:state];
    
    // 只要修改了文字，就让按钮重新计算自己的尺寸
    [self sizeToFit];
}

- (void)setImage:(UIImage *)image forState:(UIControlState)state
{
    [super setImage:image forState:state];
    
    // 只要修改了图片，就让按钮重新计算自己的尺寸
    [self sizeToFit];
}


@end
